<?php

namespace app\common\event;


use think\facade\Db;
use think\Response;
use yiqiniu\extend\library\GlobalParam;
use yiqiniu\extend\library\NodeService;
use yiqiniu\extend\library\SqlRecordLog;
use function app;
use function env;
use function request;
use function writelog;
use const API_SUCCESS;

/**
 * 记录请求日志
 */
class HttpEndEventHandler
{
    // 忽略的操作
    protected array $ignore = ['/manage/login', '/merchants/login'];

    // 需要记录的模块名
    protected array $app_names = [
        'manage', 'merchants'
    ];
    protected array $log_tables = [
        'manage' => 'system_oplog',
        'merchants' => 'merchant_oplog',
    ];

    /*
     * 表结构日志
    create table c_system_oplog
    (
        id bigint auto_increment primary key,
        op_user int not null  default 0 comment '操作人',
        app_name varchar(50)  not null  default '' comment 'app名称',
        action varchar(100)  not null  default '' comment '执行动作',
        action_title varchar(200)  not null  default '' comment '动作名称',
        request text  default ''  comment '请求内容',
        execute text  default ''  comment 'sql内容',
        create_time datetime default now() comment '创建时间',
        index idx_action(action)
    ) comment '操作日志表' ROW_FORMAT=COMPRESSED;
    */


    /**
     * 请求完成成功
     * @param Response $response
     */
    public function handle(Response $response)
    {
        $appName = app()->http->getName();
        if (in_array($appName, $this->app_names, true)) {
            // 读取env 配置忽略的操作
            $ignore = env('record_log_ignore_actions', '');
            if (!empty($ignore)) {
                $this->ignore = array_merge($this->ignore, $ignore);
            }
            $request = request();
            if ($request->isPost() && (!empty($request->post()) || !empty($request->get()))) {
                if (in_array($request->url(), $this->ignore, true)) {
                    return;
                }
                if ($data = $response->getData()) {
                    try {
                        $global = GlobalParam::getInstance();
                        if ($data['code'] === API_SUCCESS) {
                            $logData = [
                                'mer_id' => $global->get('mer_id'),
                                'op_user' => $global->get('op_user'),
                                'op_name' => $global->get('op_name'),
                                'action' => $request->url(),
                                'action_title' => NodeService::instance()->getActionTitle(),
                                'request' => json_encode($request->post(), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES),
                                'execute' => SqlRecordLog::toJson(),
                                'ip' => $request->ip(),
                            ];
                            $tbname = $this->log_tables[$appName] ?? '';
                            if (!empty($tbname)) {
                                Db::name($tbname)->insert($logData);
                            }
                        }
                    } catch (\Exception $e) {
                        writelog('请求日志记录出错：' . $e->getMessage());
                    }
                }
            }
        }

    }

}
